#region Using

using System;
using System.Collections.Specialized;
using System.Data;
using System.Text;
using BlogEngine.Core;
using BlogEngine.Core.Provider;
using BlogEngine.Core.Provider.Interfaces;

#endregion

namespace BlogEngine.Core.Provider.MSSQL
{
	/// <summary>
	/// Microsoft SQL Server Implementation of BlogProvider
	/// </summary>
	public class CISettings : ISettings
	{
		/// <summary>
		/// Loads the settings from the provider.
		/// </summary>
		/// <returns></returns>
		public StringDictionary Load()
		{
			StringDictionary dic = new StringDictionary();

			SQLManagedConnection myConn = SQLManagedConnection.GetConnection(Provider.DatabaseName);

			try
			{
				myConn.GetTextCommand("SELECT SettingName, SettingValue FROM be_Settings");

				using (IDataReader rdr = myConn.ExecuteReader())
				{
					while (rdr.Read())
						dic.Add(rdr.GetString(0), rdr.GetString(1));

					rdr.Close();
				}
			}
			finally
			{
				myConn.CloseIfNonTransactional();
			}

			return dic;
		}

		/// <summary>
		/// Saves the settings to the provider.
		/// </summary>
		/// <param name="settings"></param>
		public void Save(StringDictionary settings)
		{
			if (settings == null)
				throw new ArgumentNullException("settings");

			SQLManagedConnection myConn = SQLManagedConnection.GetConnectionForTransaction(Provider.DatabaseName);

			try
			{
				myConn.GetTextCommand("DELETE FROM be_Settings");
				myConn.ExecuteNonQuery();

				foreach (string key in settings.Keys)
				{
					myConn.GetTextCommand("INSERT INTO be_Settings (SettingName, SettingValue) VALUES (@name, @value)");
					myConn.AddInParameter("@name", DbType.String, key);
					myConn.AddInParameter("@value", DbType.String, settings[key]);
					myConn.ExecuteNonQuery();
				}

				myConn.Commit();
			}
			finally
			{
				//if commit worked then this will do nothing
				myConn.Rollback();
			}
		}
	}
}
